﻿using DoNetDrive.Common.Extensions;
using DoNetDrive.Core.Command;
using DoNetDrive.Core.Command.Text;
using DoNetDrive.Core.Packet;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _8280WEBSocket.Command.Json
{
    public class JsonCommand : TextCommand
    {
        protected object mSendObject;
        protected Action<string> mJsonResult;
        public string Reply { get; set; }
        public JsonCommand(INCommandDetail cd, object par) : base(cd, new TextCommandParameter(""))
        {
            mSendObject = par;
            _IsWaitResponse = true;
            //   mCheckResult = oCheckResult;
            _Decompile = new JsonPacketDecompile();
        }

        protected override void CreatePacket()
        {
            var setting = new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };
            _Packet = new JsonPacket(JsonConvert.SerializeObject(mSendObject, setting));
        }
        protected override void CommandNext(INPacket readPacket)
        {
            if (readPacket is JsonPacket)
            {
                var jPck = readPacket as JsonPacket;
                var sJson = jPck.GetJson();
                _Result = new JsonCommandResult(sJson);

                if (CheckJsonResult(sJson) == true)
                {
                    CommandCompleted();
                }
            }
        }
        public bool CheckJsonResult(string sRetJson)
        {
            if (sRetJson.StartsWith("{\"reply\":", StringComparison.OrdinalIgnoreCase)
                && sRetJson.IndexOf(Reply, StringComparison.OrdinalIgnoreCase) > 0)
            {
                mJsonResult?.Invoke(sRetJson);
                return true;
            }
            return false;
        }
    }
}
